package com.zjjt.dc.common.util;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.IvParameterSpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

public class DESEncryptUtil {
    public static String encrypt(DESEncryptEntity desModel, String key) throws Exception {
        DESKeySpec keySpec = new DESKeySpec(desModel.getPassword().getBytes(desModel.getOutCharset()));
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
        SecretKey secretKey = keyFactory.generateSecret(keySpec);

        IvParameterSpec ivSpec = new IvParameterSpec(desModel.getOffset().getBytes(desModel.getOutCharset()));
        Cipher cipher = Cipher.getInstance("DES/"+ desModel.getModel() + "/" + desModel.getFillCode());
        cipher.init(Cipher.ENCRYPT_MODE, secretKey, ivSpec);

        byte[] encryptedBytes = cipher.doFinal(key.getBytes(desModel.getOutCharset()));
        return Base64.getEncoder().encodeToString(encryptedBytes);
    }
    public static String decrypt(DESEncryptEntity desModel, String key) throws Exception {
        DESKeySpec keySpec = new DESKeySpec(desModel.getPassword().getBytes(desModel.getOutCharset()));
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
        SecretKey secretKey = keyFactory.generateSecret(keySpec);

        IvParameterSpec ivSpec = new IvParameterSpec(desModel.getOffset().getBytes(desModel.getOutCharset()));
        Cipher cipher = Cipher.getInstance("DES/"+ desModel.getModel() + "/" + desModel.getFillCode());
        cipher.init(Cipher.DECRYPT_MODE, secretKey, ivSpec);
        byte[] decodedData = Base64.getDecoder().decode(key);
        byte[] decryptedData = cipher.doFinal(decodedData);;
        return new String(decryptedData, StandardCharsets.UTF_8);
    }
}
